'use strict';
const db = uniCloud.database();
const creditsCollection = db.collection('xxf-credits');
const dbCmd = db.command;
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	const {
		uid,
		action
	} = event;
	if (!uid && action) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'getCreditsTotal':
			return getCreditsTotal(event);
		case 'getMyCreditList':
			return getMyCreditList(event);
		case 'addCreditRow':
			return addCreditRow(event);
		case 'minusCreditRow':
			return minusCreditRow(event);
		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};

async function minusCreditRow(params) {
	const {
		uid,
		id
	} = params;
	const minusRes = await creditsCollection.doc(id).update({
		status: -1
	});
	console.log("minusRes: ", minusRes);
	if (minusRes.updated === 1) {
		return {
			msg: 'success',
			code: 1,
			data: {}
		}
	} else {
		return {
			msg: 'fail',
			code: 0,
			data: null
		};
	}
}

async function addCreditRow(params) {
	const {
		uid,
		from,
		points
	} = params;
	const createRes = await creditsCollection.add({
		uid,
		from,
		points,
		create_time: Date.now(),
		status: 1
	});
	console.log("createRes: ", createRes);
	if (createRes) {
		return {
			msg: 'success',
			code: 1,
			data: {}
		}
	} else {
		return {
			msg: 'fail',
			code: 0,
			data: null
		};
	}
}

async function getMyCreditList(params) {
	const {
		uid
	} = params;
	const listRes = await creditsCollection.where({
		uid,
	}).get();
	console.log('listRes: ', listRes);
	return {
		msg: '',
		code: 1,
		data: {
			list: listRes.data,
		}
	};
}

async function getCreditsTotal(params) {
	const {
		uid
	} = params;
	const $ = db.command.aggregate;
	const sumCountRes = await creditsCollection
		.aggregate()
		.match({
			uid
		})
		.group({
			_id: null,
			total: $.sum('$points')
		})
		.end();
	console.log('sumCountRes: ', sumCountRes);
	if (sumCountRes.data && sumCountRes.data.length) {
		const sumRes = sumCountRes.data[0];
		return {
			msg: 'success',
			code: 1,
			data: {
				creditsTotal: sumRes.total || 0
			}
		};
	} else {
		return {
			msg: '查询失败！',
			code: 0,
			data: null
		};
	}
}